package com.xc.util;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Tool {
    private Tool() {

    }

    public static Integer strToInt(String value) {
        try {
            return Integer.valueOf(value);

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return -1;
    }

    public static Integer strToZeroInt(Object value) {
        try {

            return Integer.valueOf(value + "");

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return 0;
    }

    public static Integer strToPage(String value) {
        try {
            return Integer.parseInt(value) == 0 ? 1 : Integer.parseInt(value);

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return 1;
    }

    public static Integer strToLimit(String value) {
        try {
            return Integer.valueOf(value);

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return 20;
    }

    public static BigDecimal strToDecimal(String value) {
        try {
            return new BigDecimal(value);

        } catch (Exception e) {
//            e.printStackTrace();
        }
        return new BigDecimal("0");
    }

    /**
     * 判断是否为空
     *
     * @param value
     * @return
     */
    public static String strToDate(String value) {
        if (value == null) return "1900-1-1";
        String reg = "yyyy-MM-dd";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(reg);
        try {
            Date date = simpleDateFormat.parse(value);
            return simpleDateFormat.format(date);
        } catch (ParseException e) {
//            e.printStackTrace();
        }

        return "1900-1-1";
    }

    /**
     * 驼峰法转下划线
     *
     * @param line 源字符串
     * @return 转换后的字符串
     */
    public static String camelToUnderline(String line) {
        if (line == null || "".equals(line)) {
            return "";
        }
        line = String.valueOf(line.charAt(0)).toUpperCase().concat(line.substring(1));
        StringBuffer sb = new StringBuffer();
        Pattern pattern = Pattern.compile("[A-Z]([a-z\\d]+)?");
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {
            String word = matcher.group();
            sb.append(word.toUpperCase());
            sb.append(matcher.end() == line.length() ? "" : "_");
        }
        return sb.toString();
    }
}
